package com.wxd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wxd.reggie.common.BaseContext;
import com.wxd.reggie.common.CustomException;
import com.wxd.reggie.common.R;
import com.wxd.reggie.entity.AddressBook;
import com.wxd.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增收获地址
     *
     * @param addressBook
     */
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.save(addressBook);
        return R.success("新增成功");
    }

    /**
     * 获取地址列表
     *
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list() {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(userId != null, AddressBook::getUserId, userId);
        lqw.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = addressBookService.list(lqw);
        return R.success(list);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     */
    @PutMapping("/default")
    public R<String> defaultAddress(@RequestBody AddressBook addressBook) {
        // 1. 查出当前用户下所有的地址 将地址状态全部置为非默认状态
        LambdaUpdateWrapper<AddressBook> luw = new LambdaUpdateWrapper<>();
        luw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        luw.set(AddressBook::getIsDefault, 0);
        addressBookService.update(luw);
        // 2. 将用户所选择的地址置为默认状态
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success("设置成功");
    }

    /**
     * 获取用户的默认地址
     *
     * @return
     */
    @GetMapping("/default")
    public R<AddressBook> defaultList() {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, userId).eq(AddressBook::getIsDefault, 1);
        AddressBook addressBookOne = addressBookService.getOne(queryWrapper);
        if (addressBookOne == null) throw new CustomException("请添加默认地址");
        return R.success(addressBookOne);
    }
}
